package com.tech.thread.juc.locks.ReentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Author: zl
 * @Date: 2019/7/26 11:28
 */
public class LockInterruptiblyDemo implements Task{
    final ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void performTask() {
        try {
            reentrantLock.lockInterruptibly();
            //if it is not able to acquire lock because of other threads interrupts,
            //it will throw InterruptedException and control will go to catch block.
            try {
                if (Thread.currentThread().getName().equals("pool-1-thread-1")) {
                    Thread.currentThread().interrupt();
                    Thread.sleep(10000);
                }
                System.out.println(Thread.currentThread().getName() +": Lock acquired.");
                System.out.println("Work on progress...");
                Thread.sleep(10000);
            } finally {
                System.out.println(Thread.currentThread().getName() +": Lock released.");
                reentrantLock.unlock();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}